﻿var editor;
var flag = false;
var menuID;

function validate() {
    return $("#frm").valid();
};

function get() {
    $.post("CMS/Handlers/CMS_ArticleHandler.ashx?type=get", { ID: $("#ID").val() }, function (data) {
        $('#frm').fill(data);
        console.log(data.Cover);
        if (data.Cover != "") {
            $("#imgCover").attr("src", data.Cover);
        }
        else {
            $("#imgCover").hide();
        }
        editor.html(data.Content);
    }, 'json');
}

function save(type) {
    editor.sync();
    var content = document.getElementById('Content');
    content.value = content.value.replace(/</g, "[").replace(/>/g, "]");
    $("#frm").ajaxSubmit({
        dataType: 'json',
        beforeSubmit: function (arr, $form, options) {
            if (flag) {
                return false;
            }
            else {
                flag = true;
                return true;
            }
                
        },
        success: function (data) {
            if (data.isSuccess) {
                if (type == 1) {
                    loadPage("CMS/CMS_ArticleList.aspx?menuID=" + menuID);
                }
                else {
                    loadPage("CMS/CMS_ArticleItem.aspx?menuID=" + menuID);
                }
            }
            else {
                jalert(data.message);
            }
            flag = false;
        }
    });
}

$(function () {
    menuID = $("#MenuID").val();

    editor = KindEditor.create('#Content', {
        uploadJson: 'Controls/KindEditor/asp.net/upload_json.ashx',
        fileManagerJson: 'Controls/KindEditor/asp.net/file_manager_json.ashx',
        allowFileManager: true
    });

    if ($("#ID").val().length > 0)
        get();

    $("#btnSubmit").click(function () {
        save(1);
    })

    $("#btnContinue").click(function () {
        save(2);
    });
    
    $("#btnCancel").click(function () {
        loadPage("CMS/CMS_ArticleList.aspx?menuID=" + menuID);
    });
});
